﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoDeploy.Client
{
    internal class FileManager
    {
        private readonly ProjectConfig _config;

        public FileManager(ProjectConfig config)
        {
            this._config = config;
        }

        /// <summary>
        /// 1
        /// </summary>
        /// <param name="targetFolder"></param>
        /// <returns></returns>
        public  IEnumerable<FileInfo> GetLastestFiles(string targetFolder)
        {
            // 获取文件夹中所有文件
            var files = Directory.GetFiles(targetFolder, "*.*", SearchOption.TopDirectoryOnly)//只搜索顶层文件夹
                                 .Select(filePath => new FileInfo(filePath));

            // 找到最新的文件
            var latestFile = files.OrderByDescending(f => f.CreationTime).FirstOrDefault();

            if (latestFile == null)
            {
                Console.WriteLine("没有找到任何文件。");
                return null;
            }

            // 计算最新文件创建时间的一分钟之前的时间点
            DateTime oneMinuteBeforeLatest = latestFile.CreationTime.AddMinutes(-1);

            // 筛选出创建时间在最新文件创建时间前后一分钟内的所有文件
            var recentFiles = files.Where(f => f.CreationTime >= oneMinuteBeforeLatest && f.CreationTime <= latestFile.CreationTime);

            return recentFiles;
        }

        private IEnumerable<FileInfo> _resultFiles;

        public List<FileInfo> GetFilteredFiles(string targetDirectory)
        {
            var directoryInfo = new DirectoryInfo(targetDirectory);
            var allFiles = directoryInfo.GetFiles("*", SearchOption.AllDirectories).ToList();

            return allFiles.Where(file => !IsExcluded(file.FullName)).ToList();
        }

        private bool IsExcluded(string filePath)
        {
            foreach (var pattern in _config.Ignore)
            {
                if (pattern.EndsWith("/"))
                {
                    // 忽略指定文件夹及其子文件夹中的所有文件
                    string folderPattern = pattern.TrimEnd('/');
                    if (filePath.StartsWith(folderPattern, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
                else if (pattern.Contains("*"))
                {
                    // 使用通配符匹配文件
                    if (MatchPattern(filePath, pattern))
                    {
                        return true;
                    }
                }
                else
                {
                    // 准确匹配文件名
                    if (Path.GetFileName(filePath).Equals(pattern, StringComparison.OrdinalIgnoreCase))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        private bool MatchPattern(string filePath, string pattern)
        {
            // 将通配符模式转换为正则表达式
            string regexPattern = "^" + System.Text.RegularExpressions.Regex.Escape(pattern)
                .Replace("\\*", ".*")
                .Replace("\\?", ".") + "$";

            return System.Text.RegularExpressions.Regex.IsMatch(filePath, regexPattern, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
        }
    }
}
